package com.micro.magupe.gateway.filter;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import com.netflix.hystrix.exception.HystrixTimeoutException;

@Component
public class MicroGatewayFallbaProvider implements FallbackProvider{

	@Override
	public String getRoute() {
		return "*";
	}

	/**
	 * AbstractRibbonCommand类中的getFallbackResponse方法会调用本方法
	 */
	@Override
	public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
		String message = StringUtils.EMPTY;
		String code = StringUtils.EMPTY;
		if(cause instanceof NullPointerException) {
			message = "NullPointerException: null";
			code = "micro_10001";
		} else if(cause instanceof HystrixTimeoutException) {
			message = "HystrixTimeoutException: Gateway Timeout";
			code = "micro_10002";
		}
		
        return fallbackResponse(route, code, message);
	}

	public ClientHttpResponse fallbackResponse(String route, String code, String message){
		return new ClientHttpResponse() {
			
			@Override
			public HttpHeaders getHeaders() {
				HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                return headers;
			}
			
			@Override
			public InputStream getBody() throws IOException {
				String bodyText = String.format("{\"route\": %s,\"code\": %s,\"message\": \"Service unavailable:%s\"}", route, code, message);
                return new ByteArrayInputStream(bodyText.getBytes());
			}
			
			@Override
			public String getStatusText() throws IOException {
				return "OK";
			}
			
			@Override
			public HttpStatus getStatusCode() throws IOException {
				return HttpStatus.OK;
			}
			
			@Override
			public int getRawStatusCode() throws IOException {
				return 200;
			}
			
			@Override
			public void close() {
				
			}
		};
	}
}
